const STATUS = {
  show: 'show',
  hide: 'hide',
}

const webToast = {
  status: STATUS.hide,
  create(options) {
    this.options = options
    const {
      text, innerHtml, showActionButton, buttonText
    } = options
    const toastContainer = document.createElement('div')
    if (document.getElementById('rootToastContainer')) { return }
    toastContainer.setAttribute('id', 'rootToastContainer')
    if (innerHtml) {
      toastContainer.innerHTML = `<div class="root-toast" id="rootToast">${innerHtml}</div>`
    } else {
      toastContainer.innerHTML = showActionButton
        ? `<div class="root-toast" id="rootToast">
        <div>${text}</div>
        <span id="rootToastBtn" style="font-size: 14px;cursor: pointer">${buttonText}</span>
      </div>` : `<div class="root-toast" id="rootToast"><div>${text}</div></div>`
    }
    document.body.insertBefore(toastContainer, document.getElementById('container'))
    this.addEventListener()
  },
  addEventListener() {
    const { onClickBtn } = this.options
    const that = this
    this.rootToast = document.getElementById('rootToast')
    const rootToastBtn = document.getElementById('rootToastBtn')
    rootToastBtn && rootToastBtn.addEventListener('click', () => {
      onClickBtn && onClickBtn(that)
    })
  },
  show(options) {
    if (this.status === STATUS.show) {
      this.remove()
      this.status = STATUS.hide
    }
    this.options = options
    const that = this
    const { time = 2000, keepAlive } = options
    this.create(options)
    setTimeout(() => {
      this.status = STATUS.show
      that.rootToast.setAttribute('class', 'root-toast active')
    })
    !keepAlive && setTimeout(() => {
      that.hide()
    }, time)
  },
  hide() {
    this.status = STATUS.hide
    this.rootToast.setAttribute('class', 'root-toast')
    const that = this
    setTimeout(that.remove, 1000)
  },
  remove() {
    const rootContainer = document.getElementById('rootToastContainer')
    rootContainer && rootContainer.remove()
  },
}

export default webToast
